package org.ttitfly.ttcore.util.helper;

import java.util.Random;

import org.apache.commons.lang.StringUtils;

public class AVCHelper {
    private static String ALLCHAR = "0123456789";

    public static String SMS_SHORT_NUMBER = "10657525815201";

    private static Integer[] WEIGHTING_ARRY = new Integer[10];
    static {
        WEIGHTING_ARRY[0] = 7;
        WEIGHTING_ARRY[1] = 9;
        WEIGHTING_ARRY[2] = 9;
        WEIGHTING_ARRY[3] = 3;
        WEIGHTING_ARRY[4] = 6;
        WEIGHTING_ARRY[5] = 8;
        WEIGHTING_ARRY[6] = 0;
        WEIGHTING_ARRY[7] = 1;
        WEIGHTING_ARRY[8] = 1;
        WEIGHTING_ARRY[9] = 2;
    }

    public static String generateAVCode() {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
        }
        sb.append(getVCode(sb.toString()));
        return sb.toString();
    }

    public static boolean codeValidated(String code) {
        if (code == null || code.length() != 8 || !StringUtils.isNumeric(code)) {
            return false;
        }
        StringUtils.isNumeric(code);
        String vCode = getVCode(code);
        String xCode = code.substring(6);
        return vCode.equals(xCode);
    }

    private static String getVCode(String code) {
        String aCode = code.substring(0, 5);
        int vCode = 0;
        for (int i = 0; i < aCode.length(); i++) {
            int pos = Integer.parseInt(String.valueOf(aCode.charAt(i)));
            vCode = vCode + WEIGHTING_ARRY[pos];
        }
        return String.valueOf(vCode);
    }

    public static void main(String... s) {
        for (int i = 0; i < 1; i++) {
            String code = generateAVCode();
            System.out.println(code);
            System.out.println(codeValidated(code));
        }

    }
}
